const express = require('express')
const userRouter = require('./routes/user')
const vodRouter = require('./routes/vod')
const subjectRouter = require('./routes/subject')
const orderRouter = require('./routes/order')
const activityRouter = require('./routes/activity')
const wechatRouter = require('./routes/wechat')
const liveRouter = require('./routes/live')
const joi = require("joi")
const expressJWT = require("express-jwt")
const cors = require("cors")
const bodyParser = require('body-parser')
const { jwtSecretKey } = require("./config")

const app = express()

// 托管静态资源
app.use('/uploads', express.static('./public/upload'))
app.use(express.urlencoded({ extended: false })) // x-www-form-urlencoded
app.use(cors()) // 跨域
app.use(bodyParser.json()) // application/json

// 配置解析token的中间件
app.use(expressJWT({
  secret: jwtSecretKey,
}).unless({ path: [/^\/admin\//, /^\/ad-api\/admin\//] }))

// 全局响应方法
app.use((req, res,next) => {
  res.cc = (  err, code = 20001, dataInfo='') => {
    res.send({
      msg: err instanceof Error ? err.message : err,
      code,
      data: {
        dataInfo,
      }
    })
  }
  // 增加数据库全局方法 按条件查询
  res.getSearchSql = (searchObj) => {
    let sql = ''
    for (let key in searchObj) {
      sql += ` AND ${key} LIKE '%${searchObj[key]}%'`
    }
    return sql
  }
  // 增加数据库全局方法 按时间范围查询
  res.getRangeSql = (searchObj, keys = ['create_time', 'createTimeBegin', 'createTimeEnd']) => {
    let sql = ''
    sql += ` AND ${searchObj[keys[0]]} BETWEEN '${searchObj[keys[1]]}' AND '${searchObj[keys[2]]}'`
    return sql
  }

  next()
})

// 路由配置
app.use('/admin', userRouter)
app.use('/ad-api', vodRouter)
app.use('/ad-api', subjectRouter)
app.use('/ad-api', orderRouter)
app.use('/ad-api', activityRouter)
app.use('/ad-api', wechatRouter)
app.use('/ad-api', liveRouter)

// 错误中间件
app.use((err, req, res, next) => {
  if(err instanceof joi.ValidationError) {
    return res.send({
      status: 0,
      code: 40001,
      msg: err.message,
    })
  } else if (err.name === 'UnauthorizedError') {
    return res.send({
      status: 0,
      code: 40100,
      msg: 'token认证失败, 未经授权访问',
    })
  }
  // 未知错误
  res.send({
    status: 0,
    code: 40100,
    msg: err,
  })
})


app.listen(8080, () => {
  console.log('api serve running at http://127.0.0.1:8080')
})
